package kassiopeia.gui

import kassiopeia.commons.model.task.ParameterInstance;
import kassiopeia.gui.task.Parameter;
import kassiopeia.gui.task.Connection;
import kassiopeia.commons.model.task.PluginInstance;
import kassiopeia.gui.task.Plugin;
import kassiopeia.commons.model.task.TaskDescriptor;
import kassiopeia.gui.task.Task;

class TaskConverter {

    static TaskDescriptor convert(Task task) {
        TaskDescriptor descriptor = new TaskDescriptor()
        descriptor.name = task.name
        descriptor.description = task.description

        convertPlugins(descriptor, task)
        convertConnections(descriptor, task)

        return descriptor
    }

    private static def convertPlugins(TaskDescriptor descriptor, Task task) {
        for(Plugin plugin in task.getPlugins()) {
            String instanceId = plugin.getInstanceId()
            String pluginId = plugin.getPluginId()
            String groupId = plugin.getGroupId()
            String pluginVersion = plugin.getPluginVersion()
            PluginInstance instance = new PluginInstance(instanceId, pluginId, groupId, pluginVersion)
            convertParameters(instance,plugin)
            descriptor.getPlugins().add(instance)
        }
    }

    private static def convertConnections(TaskDescriptor descriptor, Task task) {
        for(Connection connection in task.getConnections()) {
            String fromPlugin = connection.fromInstanceId
            String fromPluginOutput = connection.fromOutputId
            String toPlugin = connection.toInstanceId
            descriptor.getConnections().add(new kassiopeia.commons.model.task.Connection(fromPlugin, fromPluginOutput, toPlugin))
        }
    }

    private static def convertParameters(PluginInstance instance, Plugin plugin) {
        for(Parameter parameter : plugin.parameters) {
            String name = parameter.getName()
            String value = parameter.getValue()
            instance.getConfiguration().add(new ParameterInstance(name, value))
        }
    }
}
